package d1_com.itheima.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private String cardID;
    private double money;
    //创建了一个锁对象（账户唯一的一个锁对象）
    private final Lock lk = new ReentrantLock();

    public Account() {
    }

    public Account(String cardID, double money) {
        this.cardID = cardID;
        this.money = money;
    }

    public String getCardID() {
        return cardID;
    }

    public void setCardID(String cardID) {
        this.cardID = cardID;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    //同步方法
    //public synchronized void drawMoney(double money) {
    public  void drawMoney(double money) {
        String name = Thread.currentThread().getName();
        lk.lock();//加锁
        //同步代码块(加锁 解锁)
        //this正好代表共享资源
        //synchronized (this) {
        try {
            if (this.money >= money) {
                System.out.println(name + "来取钱：成功~");
                this.money -= money;
                System.out.println(name + "来取钱后还剩：" + this.money);
            } else {
                System.out.println(name + "来取钱：余额不足~");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lk.unlock();//解锁
        }
        //}
    }
}
